package cn.terrence.myrpc.common.rpc.client;

import java.util.concurrent.CountDownLatch;

import cn.terrence.myrpc.common.rpc.common.ResponseFuture;
import cn.terrence.myrpc.common.rpc.log.LogUtils;

/**
 * 模拟单一长连接，多个线程使用
 * @author Administrator
 *
 */
public class Client {

	public static void main(String[] args) {
		System.out.println("客户端准备建立到服务器的连接");
		ClientNettyConnection connection = new ClientNettyConnection("127.0.0.1", 9080);
		System.out.println("客户端开始发送连接请求到服务器");
		int n = 10;
		CountDownLatch cdl = new CountDownLatch(n);
		for(int i  = 0; i < n; i ++ ) {
			new Thread(new CR(connection, cdl)).start();
		}
		try {
			cdl.await();
			//Thread.sleep(5000);//这里主要想看一下心跳包的发送
			System.out.println("客户端关闭连接");
			connection.close();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("客户端退出");
	}
	
	private static final class CR implements Runnable {
		private ClientNettyConnection connection;
		private CountDownLatch cdl;
		
		public CR(ClientNettyConnection connection, CountDownLatch cdl) {
			this.connection = connection;
			this.cdl = cdl;
		}

		public void run() {
			try {
				ResponseFuture f = connection.sendMsg("Lini.TopicService.sendTopic", "{\"req\":\"testSendTopic\"}");
				LogUtils.log("发送请求后，立即做其他事情");
				//然后获取结果，完成操作
				LogUtils.log("处理后，得出响应结果：requestId:%d,data:%s", f.getResult().getRequestId(), f.getResult().getData());
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				cdl.countDown();
			}
		}	
	}
}
